package UnionFind;

import BasicTypes.Constants;

public class QuickUnion {
	private int[] id;
	public int[] getId() {
		return id;
	}

	int distance;
	
	   public QuickUnion(int N,int Group)
	   {
		  distance = Group * Constants.COLUMESIZE * Constants.SIZE;
	      id = new int[N];
	      for (int i = 0; i < N; i++) id[i] = i;
	   }
	   
	   private int root(int i)
	   {
		  i = i - distance;
	      while (i != id[i]){
	    	  id[i] = id[id[i]];
	    	  i = id[i];
	      } 
	      return i;
	   }
	   
	   
	   public boolean find(int p, int q)
	   {
	      return root(p) == root(q);
	   }
	   
	   public void unite(int p, int q)
	   {
	      int i = root(p);
	      int j = root(q);
	      if(i < j){
	    	  id[j] = i;
	      }else{
	    	  id[i] = j;
	      }
	   }
	   
	   public void print(){
		   for(int i = 0; i < Constants.SIZE; i++){
			   for(int j = 0; j < Constants.SIZE; j++){
				   System.out.print(root(i* Constants.SIZE + j));
				   System.out.print("\t");
			   }
			   System.out.println();
		   }
	   }
	   
}
